/**
 * 类名：Sim卡业务类
 * 备注：负责Sim卡管理业务逻辑。
 * 作者：rankin
 * 日期：2016/03/4
 */
var Page = require('../models/page');
var Sim = require('../models/sim');
var Box = require('../models/boxes');
var Log = require('../models/log');

var mqttclient = require('../utils/mqttclient');
var config = require('../config/settings');

var _ = require('underscore');
var xlsx = require('node-xlsx');
var async = require('async');
var request = require('request');
var debug = require('debug')('controller:sim');
var Promise = require('bluebird');

module.exports = {

    /**
     * 跳转至首页
     */
    index: function (req, res) {

        var userid = req.session.user._id;

        var p = new Promise(function (resolve, reject) {
            if (req.session.permissionMap[1022]) {
                return resolve();
            } else {
                return Box.find({'owner': userid}).then(function (boxes) {
                    var boxids = _.pluck(boxes, 'box_id');
                    return resolve(boxids);
                }).error(function (err) {
                    return reject(err);
                });
            }
        });

        p.then(function (boxids) {

            var params = {};
            if (boxids) {
                params.box_id = boxids;
            }

            return Sim.paginate(params, {page: req.query.num, limit: 10});
        }).then(function (result) {
            var data = {};
            data.datas = result.docs;
            data.pageCount = result.pages;
            res.render('device/device_list', data);
        }).error(function (err) {
            res.send({success: false, err: err});
        });
    },
    to_create: function (req, res) {
        res.render('device/device_create');
    },
    do_create: function (req, res) {
        var data = xlsx.parse(req.files.device_data.path)[0].data;
        var count = 1;
        async.whilst(function () {
            return count < data.length;
        }, function (callback) {
            new Sim().findSimBySim(data[count][0], function (err, doc) {//检查是否存在，存在则跳过
                if (doc) {
                    debug('cunzai.............................');
                    count++;
                    callback();
                } else {
                    request.post({
                        url: config.boxwechat_api + '/hdc/applyBeacons',
                        form: {device: data[count].join(',')}
                    }, function (err, httpResponse, body) {
                        count++;
                        debug('~~~~~~~~~~~~~~~~~~~');
                        debug(body);
                        debug('~~~~~~~~~~~~~~~~~~~');
                        callback();
                    });
                }

            });

        }, function (err) {
            return res.redirect('/device/list?num=1&&sim=ok');
        });


    },
    to_wifi: function (req, res) {
        console.log(req.query.phone);
        //获取wifi数据
        new Sim().findIdBySim(req.query.phone, function (datas) {
            if (datas) {
                res.render('device/device_wifi', {id: req.query.id, phone: req.query.phone, sim: datas});
            } else {
                res.render('device/device_wifi', {id: req.query.id, phone: req.query.phone, sim: {}});
            }
        });

    },
    do_wifi: function (req, res) {
        var options = {wifissid: req.body.wifissid, wifipass: req.body.wifipass, wifilimit: req.body.wifilimit};
        new Sim().updateSimColumn(req.body.id, options, function (err) {
            //res.render('device/device_wifi');
            if (err) {
                res.render('device/device_wifi', {id: req.body.id});
            } else {
                var ssid = 'wifissid:' + req.body.wifissid;
                var pass = 'wifipass:' + req.body.wifipass
                var limit = 'wifiopen=' + req.body.wifilimit
                console.log(req.body.phone + '   ' + ssid + '   ' + pass);
                console.log('xxxxxxxxxxxxxxxxxxxxxxx');
                mqttclient.publish(req.body.phone, ssid);
                mqttclient.publish(req.body.phone, pass);
                mqttclient.publish(req.body.phone, limit);
                res.redirect('/device/list?num=1&&sim=ok');
            }

        });
    },
    create_sim: function (req, res) {
        var sim = req.body.sim;
        var operators = req.body.operators;
        var charge = req.body.charge;
        new Sim().findSimBySim(sim, function (err, doc) {
            if (doc) err = 'Sim卡已被使用,请重新输入.';
            if (err) {
                req.flash('error', err);
                return res.redirect('/box_management/create_sim');
            }
            var nSim = new Sim({
                box_id: "未绑定",
                sim: sim,
                state: 0,
                operators: operators, //sim卡所属运营商
                charge: charge //资费
            });
            nSim.save(function (err) {
                if (err) {
                    console.log(err);
                } else {
                    console.log("OK!");
                }
            });
            new Log({
                box_id: "",
                user: "管理员", //操作人
                date: new Date(), //操作日期
                operation: "生成Sim卡(卡号为:" + sim + ")" //操作内容
            }).save();
            req.flash('success', 'Sim卡已经生成.');
            return res.redirect('/device/list?num=1&&sim=ok');
        });
    },
    to_shake: function (req, res) {
        var sim = req.query.sim;
        new Sim().findUserSimById({_id: req.query.id}, function (err, doc) {
            debug('~~~~~~~~~~~~~~~~');
            console.log(doc);
            debug('~~~~~~~~~~~~~~~~~');
            res.render('device/device_shake', {
                id: req.query.id, doc: doc[0]
            });
        });

    },
    do_shake: function (req, res) {
        console.log(req.body.page_url + '~~~~~~~~~~~~~~~~~~~~~' + req.body.page_id);
        var options = {
            page_title: req.body.page_title,
            page_description: req.body.page_description,
            page_url: req.body.page_url,
            page_icon_url: req.body.page_icon_url,
            page_comment: req.body.page_comment
        };
        new Sim().updateAllBySim(req.body.id, options, function (err) {
            console.log('!!!!!!!!!!!!!!!!!');
            console.log(err);
            console.log('~~~~~~~~~~~~~');
            request.post({
                url: config.boxwechat_api + '/hdc/updatePage', form: {
                    page_id: req.body.page_id,
                    title: req.body.page_title,
                    description: req.body.page_description,
                    page_url: req.body.page_url,
                    icon_url: req.body.page_icon_url,
                    comment: req.body.page_comment

                }
            }, function (err, httpResponse, body) {
                debug('^^^^^^^^^^^^^^^^^^');
                console.log(body);
                debug('~~~~~~~~~~~~~~~~~~~');
            });
            console.log("修改Sim卡信息成功");
        });
        new Sim().findIdBySim(req.body.sim, function (datas) {
            if (datas) {
                var boxid = datas.box_id;

                //发送ibeancon配置
                mqttclient.publish(datas.sim, 'AT+MAJR' + datas.major);
                mqttclient.publish(datas.sim, 'AT+MINR' + datas.minor);
                mqttclient.publish(datas.sim, 'AT+RESET');

                new Log({
                    box_id: boxid,
                    user: "管理员", //操作人
                    date: new Date(), //操作日期
                    operation: "更新Sim卡资料" //操作内容
                }).save();
            } else {
                new Log({
                    box_id: "",
                    user: "管理员", //操作人
                    date: new Date(), //操作日期
                    operation: "更新Sim卡资料" //操作内容
                }).save();
            }
        });
        req.flash('success', 'Sim卡信息更新成功.');
        return res.redirect('/device/list?num=1&&sim=ok');
    },
    remove: function (req, res) {
        var sim = req.query.sim;
        new Sim().findIdBySim(sim, function (datas) {
            if (datas.box_id == "未绑定") {
                new Sim().removeSimBySim(sim, function (err) {
                    new Log({
                        box_id: "",
                        user: "管理员", //操作人
                        date: new Date(), //操作日期
                        operation: "删除Sim卡(号码名为:" + sim + ")" //操作内容
                    }).save();
                    req.flash('success', '删除Sim卡成功.');
                    return res.redirect('/device/list?num=1&&sim=ok');
                });
            } else {
                req.flash('error', '此Sim卡已绑定箱子，不可删除.');
                return res.redirect('/device/list?num=1&&sim=ok');
            }
        });
    }

};

